﻿#include "CCMainWindow.h"
#include <qpainter.h>
#include <qdebug.h>
#include <qtimer.h>
#include "UserMySQL.h"
#include "CommonUtils.h"
#include "SkinWindow.h"
#include "NotifyManager.h"
#include <QTreeWidgetItem>
#include "RootContactItem.h"
#include "ContactItem.h"
#include "SysTrayIcon.h"
#include "WindowManager.h"
#include "CustomProxyStyle.h"

int CCMainWindow::level = 0;

//全局变量
QString LoginUserAccount;

CCMainWindow::CCMainWindow(const QString& account, QWidget *parent)
	: account(account), 
	BasicWindow(parent) /*skinWindow(nullptr)*/
{
	ui.setupUi(this);
	// Qt::Tool: 将窗口设置为工具窗口   Qt::WindowStaysOnTopHint: 窗口始终设置在最前面
	setWindowFlags(windowFlags() | Qt::Tool | Qt::WindowStaysOnTopHint);
	init();

	LoginUserAccount = account;
}

CCMainWindow::~CCMainWindow()
{
}

void CCMainWindow::init()
{
	loadStyleSheet("CCMainWindow");
	initButton();
	ui.searchLineEdit->installEventFilter(this);
	setUserName();
	setUserHeadPixmap();
	initConnect();
	initContact();
	initSysTray();
}

void CCMainWindow::initButton()
{
	//状态按钮
	drawButtonIcon(ui.statusBtn, QRC_MAIN_PNG("StatusSucceeded"));

	//等级按钮
	initLevelButton();

	//appWidget及bottomLayout按钮
	initAppButton();
}

void CCMainWindow::initAppButton()
{
	QHBoxLayout* appLayout = new QHBoxLayout(ui.appWidget);
	appLayout->setContentsMargins(0, 0, 0, 0);
	appLayout->setSpacing(2);

	QStringList appList = { "app_1", "app_2" , "app_3" , "app_4" , "app_5" , "app_6" , "app_skin" };

	for (auto& app : appList) {
		auto btn = addOtherButton(APP_ICON(app), app);
		appLayout->addWidget(btn);
	}
	
	appLayout->addStretch();

	QStringList bottomList = { "app_7", "app_8", "app_9", "app_10" , "app_11" };
	for (auto& bottom : bottomList) {
		ui.bottomLayout_up->addWidget(addOtherButton(APP_ICON(bottom), bottom));
	}
	ui.bottomLayout_up->addStretch();
}

void CCMainWindow::initLevelButton()
{
	drawLevelButton(level);
	QTimer* timer = new QTimer(this);
	timer->setInterval(1000);
	connect(timer, &QTimer::timeout, this, [this, timer]() // 显式捕获 timer
	{
		if (level >= 99) {
			timer->stop();  // 达到上限后停止定时器
			return;
		}
		drawLevelButton(++level);
	});
	timer->start();
}

void CCMainWindow::initConnect()
{
	/*
		层叠样式表优先级：
		1.内联样式（直接在部件上设置的样式）
		2.ID选择器（如 #searchWidget）
		3.类选择器（如 QWidget）
		4.属性选择器（如[titleskin]）
		使用组合选择器时，其优先级将比单个选择器更高（更具体）
	*/
	connect(NotifyManager::instance(),
		&NotifyManager::notifySkinChanged,
		[this](){ this->updateSearchStyle(false); });

	connect(ui.sysmin, &QPushButton::clicked, this, &CCMainWindow::onMin);
	connect(ui.sysclose, &QPushButton::clicked, this, &CCMainWindow::onClose);
}
/*==================================================*/
/*
初始化根节点​​
	创建根节点 rootItem，存储数据类型标识（Qt::UserRole = 0）
	创建自定义控件 RootContactItem 显示公司名称 "德先生有限公司"
	将根节点添加到树形控件顶部，并关联自定义控件

​​动态加载子节点​​
	调用 addUserGroup 方法从数据库获取群组数据
	为每个群组创建子节点：
		存储类型标识（Qt::UserRole = 1）和群组ID
		创建 ContactItem 自定义控件显示群组头像和名称

​​事件处理机制​​
​​	单击事件​​：点击根节点时切换展开/折叠状态
​​	双击事件​​：双击子节点时触发打开聊天窗口（控制台输出模拟）
	​​展开/折叠事件​​：更新根节点控件的箭头图标状态

​​自定义样式和控件​​
	使用 CustomProxyStyle 定制树形控件外观
	RootContactItem 处理根节点的展开状态显示（箭头图标）
	ContactItem 显示群组详细信息（圆形头像 + 群组名称）

​​数据交互​​
	通过 UserMySQL 单例类访问数据库：
		getUserGroup 获取用户所属群组列表
		getGroupHeadPixmap 获取群组头像
		getGroupName 获取群组名称

​​关键设计特点​​：
	使用分层结构：根节点（公司）→ 子节点（群组）
	通过 Qt::UserRole 实现数据与视图的分离
	自定义控件提升用户体验（圆形头像、展开状态指示）
	数据库操作与界面逻辑解耦
*/
void CCMainWindow::initContact()
{
	ui.treeWidget->setStyle(new CustomProxyStyle());

	//根项
	QTreeWidgetItem* rootItem = new QTreeWidgetItem;
	rootItem->setData(0, Qt::UserRole, 0);

	RootContactItem* rootWidget = new RootContactItem(true, ui.treeWidget);
	rootWidget->setText(QString::fromLocal8Bit("德先生有限公司"));

	ui.treeWidget->addTopLevelItem(rootItem);
	ui.treeWidget->setItemWidget(rootItem, 0, rootWidget);

	//子项
	addUserGroup(rootItem);

	//连接信号与槽
	//点击
	connect(ui.treeWidget, &QTreeWidget::itemClicked, this, &CCMainWindow::onTreeItemClicked);

	//双击
	connect(ui.treeWidget, &QTreeWidget::itemDoubleClicked, this, &CCMainWindow::onTreeItemDoubleClicked);
	
	//展开
	connect(ui.treeWidget, &QTreeWidget::itemExpanded, this, &CCMainWindow::onTreeItemExpanded);

	//折叠
	connect(ui.treeWidget, &QTreeWidget::itemCollapsed, this, &CCMainWindow::onTreeItemCollapsed);
}

void CCMainWindow::addUserGroup(QTreeWidgetItem * root)
{
	auto group = UserMySQL::instance()->getUserGroup(account);
	for (auto& id : group)
	{
		auto* childItem = new QTreeWidgetItem;
		childItem->setData(0, Qt::UserRole, 1);			//子项UserRole角色下数据为1
		childItem->setData(0, Qt::UserRole + 1, id);		//子项保存群号

		auto* childWidget = new ContactItem(ui.treeWidget);

		auto headPath = UserMySQL::instance()->getGroupHeadPixmap(id);
		QPixmap head(headPath);
		QPixmap mask(QRC_MAIN_PNG("head_mask"));

		//设置群组头像
		childWidget->setHeadPixmap(CommonUtils::getRoundedPixmap(head, mask,
			childWidget->getHeadLabelSize()));

		//设置群主名称
		childWidget->setUserName(UserMySQL::instance()->getGroupName(id));

		root->addChild(childItem);
		ui.treeWidget->setItemWidget(childItem, 0, childWidget);
	}
}

void CCMainWindow::onTreeItemClicked(QTreeWidgetItem * item)
{
	bool isRoot = !(item->data(0, Qt::UserRole).toBool());
	if (isRoot)
	{
		item->setExpanded(!item->isExpanded());
	}
}

void CCMainWindow::onTreeItemDoubleClicked(QTreeWidgetItem * item)
{
	bool isChild = item->data(0, Qt::UserRole).toBool();
	if (isChild)
	{
		//qDebug() << QString::fromLocal8Bit("打开聊天窗口：") << item->data(0, Qt::UserRole + 1);
		WindowManager::instance()->addNewTalkWindow(item->data(0, Qt::UserRole + 1).toInt());
	}
}

void CCMainWindow::onTreeItemExpanded(QTreeWidgetItem * item)
{
	bool isRoot = !(item->data(0, Qt::UserRole).toBool());
	if (isRoot)
	{
		auto* rootWidget = dynamic_cast<RootContactItem*>(ui.treeWidget->itemWidget(item, 0));
		if (rootWidget)
		{
			rootWidget->setExpanded(true);
		}
	}
}

void CCMainWindow::onTreeItemCollapsed(QTreeWidgetItem * item)
{
	bool isRoot = !(item->data(0, Qt::UserRole).toBool());
	if (isRoot)
	{
		auto* rootWidget = dynamic_cast<RootContactItem*>(ui.treeWidget->itemWidget(item, 0));
		if (rootWidget)
		{
			rootWidget->setExpanded(false);
		}
	}
}

void CCMainWindow::onQuit()
{
	auto* shell = WindowManager::instance()->getTalkWindowShell();
	if (shell)
	{
		shell->close();
		//delete shell;
		shell->deleteLater();
		
	}
	QApplication::quit();
}

/*==================================================*/

void CCMainWindow::initSysTray()
{
	auto* sysTray = new SysTrayIcon(this);
	sysTray->show();
}

/*==================================================*/

void CCMainWindow::drawButtonIcon(QPushButton* btn, const QString& filePath) // 移除不必要的引用
{
	static QMap<QString, QPixmap> cache; // 静态缓存已加载图片

	QPixmap pixmap(btn->size());
	pixmap.fill(Qt::transparent);

	// 从缓存获取或加载图片
	if (!cache.contains(filePath)) {
		cache[filePath] = QPixmap(filePath);
	}
	const QPixmap& iconPixmap = cache[filePath];

	QPainter p(&pixmap);
	p.setRenderHint(QPainter::SmoothPixmapTransform); // 平滑缩放
	p.drawPixmap(
		QPointF((pixmap.width() - iconPixmap.width()) / 2.0,  // 使用浮点计算避免偏移
		(pixmap.height() - iconPixmap.height()) / 2.0),
		iconPixmap
	);

	btn->setIcon(pixmap);
	btn->setIconSize(pixmap.size());
}

QPushButton * CCMainWindow::addOtherButton(const QString & iconPath, const QString & objName, QSize size)
{
	QPushButton* btn = new QPushButton(this);

	btn->setObjectName(objName);
	btn->setFixedSize(size);
	btn->setProperty("hasborder", true);

	drawButtonIcon(btn, iconPath);

	connect(btn, &QPushButton::clicked, this, &CCMainWindow::onButtonClicked);
	return btn;
}

/*
void CCMainWindow::drawLevelButton(int level)
{
	QPixmap pixmap(ui.levelBtn->size());
	pixmap.fill(Qt::transparent);

	QPainter p(&pixmap);
	
	QPixmap lv(QRC_MAIN_PNG("lv"));
	int centerHeight = (ui.levelBtn->height() - lv.height()) / 2;

	p.drawPixmap(0, centerHeight, lv);

	int tenNum = level / 10;
	int unitNum = level % 10;

	QPixmap levelValue(QRC_MAIN_PNG("levelvalue"));

	p.drawPixmap(10, centerHeight, levelValue, tenNum * 6, 0, 6, 7);
	p.drawPixmap(16, centerHeight, levelValue, unitNum * 6, 0, 6, 7);

	ui.levelBtn->setIcon(pixmap);
	ui.levelBtn->setIconSize(ui.levelBtn->size());
}
*/

void CCMainWindow::drawLevelButton(int level)
{
	// 1. 图片缓存 (静态成员变量或函数内静态变量)
	static QPixmap lvPixmap(QRC_MAIN_PNG("lv"));
	static QPixmap levelValuePixmap(QRC_MAIN_PNG("levelvalue"));

	// 2. 按钮尺寸和数字尺寸常量
	const QSize btnSize = ui.levelBtn->size();
	constexpr int DIGIT_WIDTH = 6;
	constexpr int DIGIT_HEIGHT = 7;
	constexpr int DIGIT_SPACING = 0; // 数字间距（根据实际图像调整）

	// 3. 绘制基础
	QPixmap pixmap(btnSize);
	pixmap.fill(Qt::transparent);
	QPainter p(&pixmap);
	p.setRenderHint(QPainter::SmoothPixmapTransform); // 平滑绘制

	// 4. 绘制 LV 图标
	const int centerY = (btnSize.height() - lvPixmap.height()) / 2;
	p.drawPixmap(0, centerY, lvPixmap);

	// 5. 分解十位和个位数字
	const int tenNum = qBound(0, level / 10, 9);  // 限制范围 0-9
	const int unitNum = qBound(0, level % 10, 9);

	// 6. 绘制数字（提取为 lambda 或成员函数）
	auto drawDigit = [&](int x, int digit) {
		p.drawPixmap(
			x, centerY,
			levelValuePixmap,
			digit * DIGIT_WIDTH, 0,
			DIGIT_WIDTH, DIGIT_HEIGHT
		);
	};

	const int baseX = 10; // LV 图标右侧的起始位置
	drawDigit(baseX, tenNum);
	drawDigit(baseX + DIGIT_WIDTH + DIGIT_SPACING, unitNum);

	// 7. 设置按钮图标
	ui.levelBtn->setIcon(pixmap);
	ui.levelBtn->setIconSize(btnSize);
}

void CCMainWindow::updateSearchStyle(bool hasFocus)
{
	if (hasFocus)	//有焦点
	{
		ui.searchBtn->setStyleSheet(QString(
			"QWidget#searchWidget {"
				"background-color: rgb(255, 255, 255);"
				"border-bottom: 1px solid rgba(%1, %2, %3, 100);"
			"}"
			"QPushButton#searchBtn {"
				"border-image:url(:Resources/MainWindow/search/main_search_deldown.png);"
			"}"
			"QPushButton#searchBtn:hover {"
				"border-image:url(:Resources/MainWindow/search/main_search_delhighlight.png);"
			"}"
			"QPushButton#searchBtn:pressed {"
				"border-image:url(:Resources/MainWindow/search/main_search_delhighdown.png);"
			"}"
		).arg(skinColor.red()).arg(skinColor.green()).arg(skinColor.blue()));
	}
	else {	//无焦点
		ui.searchBtn->setStyleSheet(QString(
			"QWidget#searchWidget {"
				"background-color: rgb(%1, %2, %3, 50);"
				"border-bottom: 1px solid rgba(%1, %2, %3, 30);"
			"}"
			"QPushButton#searchBtn {"
				"border-image:url(:Resources/MainWindow/search/search_icon.png);"
			"}"
		).arg(skinColor.red()).arg(skinColor.green()).arg(skinColor.blue()));
	}
}

void CCMainWindow::setUserName()
{
	QString name = UserMySQL::instance()->getUserName(account);

	name = ui.nameLabel->fontMetrics().elidedText(name, Qt::ElideRight, ui.nameLabel->width());

	QFont font;
	font.setBold(true);                   // 加粗
	font.setPixelSize(17);                // 字号17像素
	font.setFamily("Microsoft YaHei");    // 微软雅黑字体

	ui.nameLabel->setStyleSheet("color: white");
	ui.nameLabel->setFont(font);
	ui.nameLabel->setText(name);
}

void CCMainWindow::setUserHeadPixmap()
{
	/*优化：可以在ini目录下把head的路径存储下来，这样就不用每次登陆时都是默认的头像*/
	QString headPath = UserMySQL::instance()->getUserHeadPixmap(account);

	QPixmap head(headPath);
	QPixmap mask(QRC_MAIN_PNG("head_mask"));

	auto pixmap = CommonUtils::getRoundedPixmap(head, mask, ui.headLabel->size());
	ui.headLabel->setPixmap(pixmap);
}

bool CCMainWindow::eventFilter(QObject * watched, QEvent * event)
{
	if (watched == ui.searchLineEdit)
	{
		if (event->type() == QEvent::FocusIn)		//如果有焦点
		{
			updateSearchStyle(true);
			return false;
		}
		else if(event->type() == QEvent::FocusOut)	//如果没有焦点
		{
			updateSearchStyle(false);
			return false;
		}
	}

	return BasicWindow::eventFilter(watched, event);
}

void CCMainWindow::onButtonClicked()
{
	if (sender()->objectName() == "app_skin")
	{
		auto* skinWindow = new SkinWindow;
		skinWindow->show();
	}
}